import { defineStore } from "pinia";
import { computed, ref } from "vue";
import { getAllMenusApi } from "../api/menu";
import router from "../router/index";
import type { RouteRecordRaw } from "vue-router";
// 定义菜单项接口
export interface MenuItem {
  id?: string;
  title: string;
  route: string;
  component: string;
  children?: MenuItem[];
  icon?: string;
  hidden?: boolean;
  meta?: {
    title?: string;
    icon?: string;
    [key: string]: any;
  };
}

// 定义菜单接口
export interface Menus {
  menus: MenuItem[];
}

// 加载vue组件
const layoutModules = import.meta.glob("/src/views/**/*.vue");

export const useMenuStore = defineStore("menu", () => {
  // 定义状态
  const menus = ref<Menus>({
    menus: [],
  });

  // 获取所有菜单
  const allMenus = computed(() => menus.value.menus);

  // 将菜单转换为路由
  const menuToRoute = (menu: MenuItem): RouteRecordRaw => {
    const componentPath = `/src/views/${menu.component}.vue`;
    const component = layoutModules[componentPath];
   
    const route: RouteRecordRaw = {
      path: menu.route,
      name: menu.id || menu.title.replace(/\s+/g, "_").toLowerCase(),
      component:menu.component ? component : null,
      children:
        menu?.children?.filter((child) => child.route).map(menuToRoute) || [],
      meta: {
        title: menu.title,
        icon: menu.icon,
        hidden: menu.hidden,
      },
    };

    // if (menu.children && menu.children.length > 0) {
    //   route.children = menu.children.filter(child => child.route).map(menuToRoute);
    // }

    return route;
  };

  // 设置菜单
  const setMenus = (menuList: MenuItem[]) => {
    menus.value.menus = menuList;

    // 保存到localStorage
    saveMenusToStorage();
  };

  // 存储动态添加的路由，用于后续清除
  const dynamicRoutes = ref<RouteRecordRaw[]>([]);

  // 清空菜单
  const clearMenus = () => {
    menus.value = {
      menus: [],
    };

    // 从localStorage移除
    localStorage.removeItem("menus");
  };

  // 清除动态添加的路由
  const clearDynamicRoutes = () => {
    if (dynamicRoutes.value.length > 0) {
      dynamicRoutes.value.forEach((route) => {
        router.removeRoute(route.name!);
      });
      dynamicRoutes.value = [];
    }
  };

  // 保存菜单到localStorage
  const saveMenusToStorage = () => {
    try {
      const data = {
        menus: menus.value.menus,
      };
      localStorage.setItem("menus", JSON.stringify(data));
    } catch (error) {
      console.error("保存菜单到localStorage失败:", error);
    }
  };

  // 从localStorage加载菜单
  const loadMenusFromStorage = () => {
    try {
      const stored = localStorage.getItem("menus");
      if (stored) {
        const data = JSON.parse(stored);
        menus.value.menus = data.menus || [];
      }
    } catch (error) {
      console.error("从localStorage加载菜单失败:", error);
    }
  };

  // 获取所有菜单（不进行权限过滤）
  const getFilteredMenus = computed(() => {
    const filterMenu = (menuList: MenuItem[]): MenuItem[] => {
      return menuList
        .filter((menu) => !menu.hidden)
        .map((menu) => ({
          ...menu,
          children: menu.children ? filterMenu(menu.children) : [],
        }))
        .filter((menu) => menu.children.length > 0 || menu.route); // 确保没有空的菜单项
    };

    return filterMenu(menus.value.menus);
  });

  // 通过接口获取用户的菜单
  function getAllMenus() {
    // 调用接口获取菜单数据
    getAllMenusApi().then((res: any) => {
      // 先清除旧的动态路由
      clearDynamicRoutes();

      setMenus(res.data);
      // 将菜单转换为路由并添加到路由表
      const mainRoute = router.getRoutes().find((route) => route.path === "/");
      if (mainRoute && res.data && res.data.length > 0) {
        // 处理顶层菜单，添加为mainRoute的子路由
        const newRoutes = res.data
          .filter((menu: MenuItem) => menu.route)
          .map(menuToRoute);

        newRoutes.forEach((route: any) => {
          // 为每个路由添加认证要求
          if (!route.meta) route.meta = {};
          route.meta.requiresAuth = true;

          // 添加到主路由下
          router.addRoute("main", route);
          dynamicRoutes.value.push(route);
        });

        // 设置菜单数据

        // 触发路由更新
        router.replace(router.currentRoute.value.fullPath);
      }
    });
  }
  return {
    // 状态
    menus,
    allMenus,

    getFilteredMenus,

    // 操作
    setMenus,
    clearMenus,
    clearDynamicRoutes,
    loadMenusFromStorage,
    getAllMenus,
  };
});
